﻿using LuaInterface;
using UnityEngine;
using UnityEngine.UI;

namespace Framework.UGUI
{
	public class SliderWrap : MonoBehaviour
	{
		public static SliderWrap Get(GameObject go)
		{
			Slider slider = go.GetComponent<Slider>();
			if (slider != null)
			{
				return go.OnceAddComponent<SliderWrap>();
			}
			return null;
		}

		public static SliderWrap GetWithPath(GameObject go, string path)
		{
			var sliderTransform = go.transform.Find(path);
			if (sliderTransform != null)
			{
				return Get(sliderTransform.gameObject);
			}
			return null;
		}

		private Slider _slider;
		public Slider slider
		{
			get
			{
				if (_slider == null)
				{
					_slider = gameObject.GetComponent<Slider>();
				}
				return _slider;
			}
		}

		private GeneralCallBackWithParam _onValueChangedCallback;

		public void AddOnValueChanged(LuaFunction onValueChanged, LuaTable onValueChangedTarget, object param = null)
		{
            GeneralCallBackWithParam.GetOrReuse(ref _onValueChangedCallback, null, onValueChanged, onValueChangedTarget, param);
			slider.onValueChanged.RemoveListener(OnValueChanged);
			slider.onValueChanged.AddListener(OnValueChanged);
		}

		public void RemoveOnValueChanged()
		{
			_clearCallBack();
			slider.onValueChanged.RemoveListener(OnValueChanged);
		}

		public float GetValue()
		{
			return slider.value;
		}

		public void SetValue(float value)
		{
			slider.value = value;
		}

		private void OnValueChanged(float value)
		{
			if (_onValueChangedCallback != null)
			{
				GeneralCallBackWithParam.Invoke(ref _onValueChangedCallback, value);
			}
		}

		private void _clearCallBack()
		{
            GeneralCallBackWithParam.RecycleInst(ref _onValueChangedCallback);
		}

		void OnDestroy()
		{
			if (_onValueChangedCallback != null)
			{
				UIEventDebugger.LogUIEventError("SliderWrap", gameObject);
			}
			_clearCallBack();
		}
	}
}